//
//  CameraTool.swift
//  ZhiTing
//
//  Created by zy on 2022/6/1.
//

import UIKit
#if !(targetEnvironment(simulator))
class CameraTool: NSObject {
    
    var completedCallback: ((_ cameraData: CameraModel) -> ())?

    //摄像机信息
    var cameraData = CameraModel()
    //生成的随机密码
    var tempPwd = ""
    
    override init() {
        super.init()
        VSNet.shareinstance()?.pppp_Initialize()
        VSNet.shareinstance()?.xqp2P_NetworkDetect()
        VSNet.shareinstance()?.xqp2P_Initialize()
    }

    convenience init(identifier: String) {
        self.init()
    }

    deinit {
    }
    
    
    public func releaseAll(){
        VSNet.shareinstance().stop(cameraData.uid)
        DispatchQueue.global().async {
            VSNet.shareinstance()?.pppp_DeInitialize()
            VSNet.shareinstance()?.xqp2P_DeInitialize()
        }
    }
    //连接摄像头
    public func connectVideo(uid: String, pwd: String){
        let camera = CameraCache.getCamera(uid: uid)
        let p2pString = getPPPPString(strDID: uid)

        let isVuid = VSNet.shareinstance()?.isVUID(uid) ?? false
        if isVuid {
            VSNet.shareinstance()?.startVUID(camera.tmpdid, withPassWord: pwd, initializeStr: p2pString, lanSearch: 1, id: nil, add: false, vuid: uid, lastonlineTimestamp: UInt(camera.lastTime ?? 0), withDelegate: self)
            //设置状态代理
            VSNet.shareinstance()?.setStatusDelegate(uid, withDelegate:self)
            //设置功能代理
            VSNet.shareinstance().setControlDelegate(uid, withDelegate: self)
        }else{
                let nRet = VSNet.shareinstance()?.start(uid, withUser:"admin", withPassWord:pwd, initializeStr: nil, lanSearch: 1)
                if nRet == false {
                   DispatchQueue.main.async {[weak self] in
                       VSNet.shareinstance()?.start(uid, withUser:"admin", withPassWord:pwd, initializeStr: nil, lanSearch: 1)
                       //设置连接状态回调代理
                       VSNet.shareinstance()?.setStatusDelegate(uid, withDelegate: self)
                   }
               }else{
                   
               }
        }
    }

    private func getPPPPString(strDID: String) -> String? {
        if strDID.uppercased().contains("VSTG") {
            return "EEGDFHBOKCIGGFJPECHIFNEBGJNLHOMIHEFJBADPAGJELNKJDKANCBPJGHLAIALAADMDKPDGOENEBECCIK:vstarcam2018"
        } else if strDID.uppercased().contains("VSTH") {
            return "EEGDFHBLKGJIGEJLEKGOFMEDHAMHHJNAGGFABMCOBGJOLHLJDFAFCPPHGILKIKLMANNHKEDKOINIBNCPJOMK:vstarcam2018"
        } else if strDID.uppercased().contains("VSTJ") {
            return "EEGDFHBLKGJIGEJNEOHEFBEIGANCHHMBHIFEAHDEAMJCKCKJDJAFDDPPHLKJIHLMBENHKDCHPHNJBODA:vstarcam2019"
        } else if strDID.uppercased().contains("VSTK") {
            return "EBGDEJBJKGJFGJJBEFHPFCEKHGNMHNNMHMFFBICPAJJNLDLLDHACCNONGLLPJGLKANMJLDDHODMEBOCIJEMA:vstarcam2019"
        } else if strDID.uppercased().contains("VSTM") {
            return "EBGEEOBOKHJNHGJGEAGAEPEPHDMGHINBGIECBBCBBJIKLKLCCDBBCFODHLKLJJKPBOMELECKPNMNAICEJCNNJH:vstarcam2019"
        } else if strDID.uppercased().contains("VSTN") {
            return "EEGDFHBBKBIFGAIAFGHDFLFJGJNIGEMOHFFPAMDMAAIIKBKNCDBDDMOGHLKCJCKFBFMPLMCBPEMG:vstarcam2019"
        } else if strDID.uppercased().contains("VSTL") {
            return "EEGDFHBLKGJIGEJIEIGNFPEEHGNMHPNBGOFIBECEBLJDLMLGDKAPCNPFGOLLJFLJAOMKLBDFOGMAAFCJJPNFJP:vstarcam2019"
        } else if strDID.uppercased().contains("VSTP") {
            return "EEGDFHBLKGJIGEJLEIGJFLENHLNBHCNMGAFGBNCOAIJMLKKODNALCCPKGBLHJLLHAHMBKNDFOGNGBDCIJFMB:vstarcam2019"
        } else if strDID.uppercased().contains("VSTF") {
            return "HZLXEJIALKHYATPCHULNSVLMEELSHWIHPFIBAOHXIDICSQEHENEKPAARSTELERPDLNEPLKEILPHUHXHZEJEEEHEGEM-$$"
        } else if strDID.uppercased().contains("VSTD") {
            return "HZLXSXIALKHYEIEJHUASLMHWEESUEKAUIHPHSWAOSTEMENSQPDLRLNPAPEPGEPERIBLQLKHXELEHHULOEGIAEEHYEIEK-$$"
        } else if strDID.uppercased().contains("VSTA") {
            return "EFGFFBBOKAIEGHJAEDHJFEEOHMNGDCNJCDFKAKHLEBJHKEKMCAFCDLLLHAOCJPPMBHMNOMCJKGJEBGGHJHIOMFBDNPKNFEGCEGCBGCALMFOHBCGMFK"
        } else if strDID.uppercased().contains("VSTB") {
            return "ADCBBFAOPPJAHGJGBBGLFLAGDBJJHNJGGMBFBKHIBBNKOKLDHOBHCBOEHOKJJJKJBPMFLGCPPJMJAPDOIPNL"
        } else if strDID.uppercased().contains("VSTC") {
            return "ADCBBFAOPPJAHGJGBBGLFLAGDBJJHNJGGMBFBKHIBBNKOKLDHOBHCBOEHOKJJJKJBPMFLGCPPJMJAPDOIPNL"
        } else {
            return nil
        }
    }
}


extension CameraTool: VSNetControlProtocol {
    func vsNetControl(_ deviceIdentity: String!, commandType comType: Int, buffer retString: String!, length: Int32, charBuffer buffer: UnsafeMutablePointer<CChar>!) {
        print("VSNet返回数据 UID:\(String(describing: deviceIdentity)), comtype \(comType)")
        switch comType {
        case Int(CGI_IESET_USER):
            let result: Int = Int(subValueByKeyString(key: "result=", retString: retString).replacingOccurrences(of: " ", with: "")) ?? 1
            if result == 0 {//设置成功
                //重启设备
                VSNet.shareinstance().sendCgiCommand(withCgi: "reboot.cgi?", withIdentity: cameraData.uid)
                self.cameraData.pwd = self.tempPwd
                //注册摄像头
                self.completedCallback?(self.cameraData)
            }else{
                //设置失败
                DispatchQueue.main.async {[weak self] in
                    guard let self = self else {return}
                    SceneDelegate.shared.window?.makeToast("摄像头添加失败，请检查wifi或重新设置")
                }
            }
        case Int(CGI_IEGET_PARAM):
            print(retString as Any)
        default:
            break
        }

    }
    
    //根据key截取内容
    private func subValueByKeyString(key: String, retString: String) -> String{
        let result = retString.components(separatedBy: key).last?.components(separatedBy: ";").first?.replacingOccurrences(of: "\"", with: "")
        return result ?? ""
    }

}

extension CameraTool: VSNetStatueProtocol {
    func vsNetStatus(_ deviceIdentity: String!, statusType: Int, status: Int) {
        
    }
    
    func vsNetStatus(fromVUID strVUID: String!, uid strUID: String!, statusType: Int, status: Int) {
        print("statusType: \(statusType) status: \(status)")
        if statusType == VSNET_NOTIFY_TYPE_VUIDSTATUS.rawValue {

            switch status {
            case Int(VUIDSTATUS_CONNECTING.rawValue):
                //正在连接中
                DispatchQueue.main.async {
//                    SceneDelegate.shared.window?.makeToast("摄像头正在连接中")
                }
            case Int(VUIDSTATUS_CONNECT_TIMEOUT.rawValue):
                //连接超时
                DispatchQueue.main.async {
                    SceneDelegate.shared.window?.makeToast("摄像头连接超时")
                }
                VSNet.shareinstance().stop(self.cameraData.uid)
            case Int(VUIDSTATUS_DEVICE_NOT_ON_LINE.rawValue):
                //设备离线
                DispatchQueue.main.async {
                    SceneDelegate.shared.window?.makeToast("摄像头已离线")
                }
                VSNet.shareinstance().stop(self.cameraData.uid)
            case Int(VUIDSTATUS_CONNECT_FAILED.rawValue):
                //设备连接失败
                DispatchQueue.main.async {
                    SceneDelegate.shared.window?.makeToast("摄像头连接失败")
                }
                VSNet.shareinstance().stop(self.cameraData.uid)
            case Int(VUIDSTATUS_INVALID_USER_PWD.rawValue):
                //用户名或密码错误
                DispatchQueue.main.async {
                    SceneDelegate.shared.window?.makeToast("用户名或密码错误")
                }
                VSNet.shareinstance().stop(self.cameraData.uid)
            case Int(VUIDSTATUS_ON_LINE.rawValue):
                //设备在线
                //连接成功，在线
                DispatchQueue.main.async {[weak self] in
                    guard let self = self else { return }
                    
                    DispatchQueue.global().async {
                        //设置随机密码
                        self.tempPwd = "\(Int(arc4random_uniform(10)))\(Int(arc4random_uniform(10)))\(Int(arc4random_uniform(10)))\(Int(arc4random_uniform(10)))\(Int(arc4random_uniform(10)))\(Int(arc4random_uniform(10)))"
                        print("随机密码：\(self.tempPwd)")
                        let cgi = String(format: "set_users.cgi?&user1=%@&user2=%@&user3=%@&pwd1=%@&pwd2=%@&pwd3=%@&", "","","admin","","",self.tempPwd)
                        VSNet.shareinstance().sendCgiCommand(withCgi: cgi, withIdentity: self.cameraData.uid)
                    }
                }

            default:
                break
            }
            
            
            if(VUIDSTATUS_VUID_VERIFICATION_FAIL.rawValue == status || VUIDSTATUS_VUID_VERIFICATION_UIDCHANGE.rawValue == status)
            {
                //延时3秒再去连接
                DispatchQueue.main.asyncAfter(deadline: .now() + 3) { [weak self] in
                    VSNet.shareinstance()?.startVUID(nil, withPassWord:self?.cameraData.pwd, initializeStr: nil, lanSearch: 1, id: nil, add: false, vuid: strVUID, lastonlineTimestamp: 0, withDelegate: self)

                }
            }
            
            return
        } else if statusType == VSNET_NOTIFY_TYPE_VUIDTIME.rawValue {
            //更新已连接的VUID时间
            CameraCache.updateVUIDLastConnetTime(did: self.cameraData.uid ?? "", tmpDid: strUID, time: status)
        }

    }
    
}

#endif
